In the first & second part of this three part series of JavaScript, we took a look at some of the concepts like let and const, type conversion, primitive and reference data types, switches and Hoisting.
JavaScript Essentials - Part I: Variables and Data Types
JavaScript Essentials - Part II: Switches, Block Scopes and String Methods
Note: In this article, we will go through some more concepts of JavaScript.
Template literals improve the code readability, look better, and provide features such as:
String interpolation
Embedded expressions
Multiline strings without hacks
String formatting
String tagging for safe HTML escaping, localization and more.
It will result in the same as concatenating two strings.
Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<html><body></body><script>//template literalsconst firstname = 'jay';
const lastname = 'desai';
const age = 26;
const city = 'Mumbai';
const address = 'Kandivali';
let html;
html = `
{firstname}
{lastname}
{age}
{city}
{address}
`;
document.body.innerHTML = html;
</script></html>
Output:
Firstname: jay
Lastname: desai
Age: 26
City: Mumbai
Address: Colaba
We will not be going into much detail on object-oriented programming, but we will learn various ways of accessing the object and adding properties to it.
There are two ways to add new properties to an object:
1 2 3 4
let obj = { key1: "value1", key2: "value2" };
Using dot notation:
1
obj.key3 = "value3";
Using square bracket notation:
1
obj["key3"] = "value3";
ES6 way to add the properties to the object:
1
2
3
Object.assign(obj, {
key3: "value3"
});
Output for all above execution is same:
1
2
3
4
5
console.log(obj) {
key1: "value1",
key2: "value2",
key3: "value3"
}
The Math object is used to perform mathematical operations on numbers.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//match object usage
pi = Math.PI
euler_constant = Math.E
round_val = Math.round(50.8)
ceil_val = Math.ceil(40.5)
floor_val = Math.floor(8.9)
max_val = Math.max(4, 5, 6, 7, 100, 200)
pow_val = Math.pow(4, 2)
sqrt_val = Math.sqrt(81)
abs_val = Math.abs(-100)
min_val = Math.min(2, 3, 4, 5, 0, -1)
console.log(pi) //3.141592653589793
console.log(euler_constant) //2.718281828459045
console.log(round_val) //51
console.log(ceil_val) //41
console.log(floor_val) //8
console.log(max_val) //200
console.log(pow_val) //16
console.log(sqrt_val) //9
console.log(abs_val) //100
console.log(min_val) // -1
Date and time are important concepts in programming. JavaScript has the date object inbuilt. Let’s explore by going through some examples.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// Date and Time//todays date
const today = new Date()
//day of the week
let day = today.getDay()
//get the current year
let year = today.getFullYear()
//get the current month
let month = today.getMonth()
//get the current hours
let hrs = today.getHours()
//get the current minutes
let min = today.getMinutes()
//get the current seconds
let sec = today.getSeconds()
console.log(today);
console.log(day);
console.log(year);
console.log(month);
console.log(hrs);
console.log(min);
console.log(sec);
Tue Apr 16 2019 17: 07: 46 GMT + 0530(India Standard Time)
22019317746803
let date_ = new Date('April 15, 2019 23:15:30');
date_.setFullYear(2020);
console.log(date_.getFullYear());
// expected output: 2020
date_.setFullYear(0);
console.log(date_.getFullYear());
// expected output: 0
The Array object is used to store multiple values in a single variable. We will be looking at creating the arrays and mutating them.
Example:
Join Arrays - Using the concat method
1 2 3 4 5
//create some array let num1 = [1, 2, 3, 4]; let num2 = new Array(5, 6, 7, 8); let concat_num1_num2 = num1.concat(num2); console.log(concat_num1_num2); //[1,2,3,4,5,6,7,8]
Let’s create some more arrays
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
//create some more arrays
const numbers = [1, 2, 3, 4, 5, 6, 7];
const numbers2 = new Array(8, 9, 10, 11, 12);
const fruit = ['Apple', 'Banana', 'Orange', 'Pear'];
// Get array length
let values;
values = numbers.length;
console.log(values); // 7
// Check if is array
values = Array.isArray(numbers);
console.log(values); //true
// Get single value
values = numbers[3];
console.log(values); //4
values = numbers[0];
console.log(values); //1
// Insert into array
numbers[2] = 100;
console.log(numbers); //(7) [1, 2, 100, 4, 5, 6, 7]
// Find index of value
values = numbers.indexOf(5);
console.log(values); //4
Map
.map() method exists on the array prototype. It utilizes the return value and returns a new array and the original array remains unchanged.
Example:
1
2
3
4
5
6
7
8
9
10
//.map() function usage
let numbers_array_original = [1, 2, 3, 4, 5, 6];
let new_number_array;
new_number_array = numbers_array_original.map((num) => {
return num * 2;
});
console.log(new_number_array); // new array
console.log(numbers_array_original); // original array unchanged
Output:
1
2
(6)[2, 4, 6, 8, 10, 12]
(6)[1, 2, 3, 4, 5, 6]
Filter
The filter() function will go through each element of the array and desired array output with sanitized values are expected.
Example:
1
2
3
4
5
6
7
8
9
10
11
12
let numbers_array_original = [1, 2, 3, 4, 5, 6];
let new_number_array;
new_number_array = numbers_array_original.map((num) => {
return num * 2;
})
.filter((data) => {
return data !== 10 && data > 6;
});
console.log(new_number_array);
console.log(numbers_array_original);
Output:
1
2
(2)[8, 12]
(6)[1, 2, 3, 4, 5, 6]
Here the map() method will return the array with each element getting multiplied with 2 and the filter function will return the number array with value 10 and elements having a value greater than 6.
Reduce
When the transformation of an array is required, using a map would be more desirable as it is easy to read.
Reduce works similar to map, but it adds more flexibility with the output we desire. If we wanted to use a map to transform our array into a new object, we couldn’t do it. In this case, we will have to use reduce.
The first argument of the reduce function is the callback which is called accumulator, the second argument is the value of the array and the third argument is the index of the element of an array
Example:
Using reduce in a similar way as we do for map:
1
2
3
4
5
6
7
8
9
10
let numbers_array_original = [1, 2, 3, 4, 5, 6];
let new_number_array;
new_number_array = numbers_array_original.reduce((accumulator, value, index) => {
accumulator[index] = value * 5;
return accumulator;
}, [])
console.log(new_number_array);
console.log(numbers_array_original);
Output:
1
2
(6)[5, 10, 15, 20, 25, 30]
(6)[1, 2, 3, 4, 5, 6]
Convert the array into an object with reduce. Conversion to other data type is not possible with map.
1
2
3
4
5
6
7
new_number_array = numbers_array_original.reduce((accumulator, value, index) => {
accumulator[value] = true;
return accumulator;
}, {})
console.log(new_number_array);
console.log(numbers_array_original);
Output:
1
2
3
4
5
6
7
8
9
10
{
1: true,
2: true,
3: true,
4: true,
5: true,
6: true
}
(6)[1, 2, 3, 4, 5, 6]
I hope this post helped you understand JavaScript a little better. You can learn Callback, Promises, and Async/Await here. If you liked this article, please feel free to comment in the forum. Cheers!